package com.ts.manage_media.service;

import com.ts.framework.domain.media.MediaFile;
import com.ts.framework.domain.media.request.QueryMediaFileRequest;
import com.ts.framework.model.response.CommonCode;
import com.ts.framework.model.response.QueryResponseResult;
import com.ts.framework.model.response.QueryResult;
import com.ts.manage_media.dao.MediaFileRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MediaFileService {
    @Autowired
    private MediaFileRepository mediaFileRepository;

    public QueryResponseResult findList(Integer page, Integer size, QueryMediaFileRequest queryMediaFileRequest) {
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        page = page - 1;
        //设置分页条件
        Pageable pageable = PageRequest.of(page, size);

        //设置查询条件
        if (queryMediaFileRequest == null) {
            queryMediaFileRequest = new QueryMediaFileRequest();
        }
        MediaFile mediaFile = new MediaFile();
        ExampleMatcher matching = ExampleMatcher.matching();
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getTag())) {
            mediaFile.setTag(queryMediaFileRequest.getTag());
            matching = matching.withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains());
        }
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getProcessStatus())) {
            mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
        }
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getFileOriginalName())) {
            mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
            matching = matching.withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains());
        }

        Example<MediaFile> example = Example.of(mediaFile, matching);

        Page<MediaFile> page1 = mediaFileRepository.findAll(example, pageable);
        long totalElements = page1.getTotalElements();
        List<MediaFile> content = page1.getContent();
        QueryResult<MediaFile> queryResult = new QueryResult<>();
        queryResult.setList(content);
        queryResult.setTotal(totalElements);
        QueryResponseResult result = new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        return result;
    }
}
